<?php
namespace app\admin\controller;

class Category extends Base
{
    private $obj;

    public function _initialize(){
        $this->obj = model('Category');
    }

    public function index()
    {
        $parent_id = input('parent_id', 0, 'intval');
        $categorys = $this->obj->getCategorysByParentId($parent_id, ['neq',-1]);

        $p = new \Page($categorys);
        $this->assign([
            'categorys' => $categorys,
            'p' => $p,
        ]);
        return $this->fetch();
    }

    public function add()
    {
        $categorys = $this->obj->getCategorysByParentId();
        $this->assign([
            'categorys' => $categorys,
        ]);
        return $this->fetch();
    }

    public function save(){
        if(!request()->isPost()){
            return $this->error('非法请求');
        }
        $data = input('post.');
        $validate = validate('Category');
        if(!$validate->scene('add')->check($data)){
            $this->error($validate->getError());
        }

        if(!empty($data['id'])){
            $result = $this->obj->save($data, ['id' => intval($data['id'])]);
            if($result){
                // $this->success('更新成功',url('category/index'));
                return getMessege(1,'更新成功','index');
            }else{
                $this->error('更新失败');
            }
            return;
        }

        // 把$data提交给model入库
        $res = $this->obj->add($data);
        if($res){
            $this->error('添加分类成功',url('category/index'));
        }else{
            $this->success('添加分类失败');
        }
    }

    public function edit($id = 0){
        if(intval($id) < 1){
            $this->error('ID不合法');
        }

        $category = $this->obj->get($id);

        $categorys = $this->obj->getCategorysByParentId();
        $this->assign([
            'categorys' => $categorys,
            'category' => $category,
        ]);
        return $this->fetch();
    }

    public function listorder($id,$listorder){
        $res = $this->obj->save(['listorder' => $listorder], ['id' => $id]);
        if($res){
            $this->result($_SERVER['HTTP_REFERER'],1,'排序成功');
        }else{
            $this->result($_SERVER['HTTP_REFERER'],0,'排序失败');
        }
    }

    // public function status(){
    //     $data = input('get.');

    //     $validate = validate('Category');
    //     if(!$validate->scene('status')->check($data)){
    //         $this->error($validate->getError());
    //     }

    //     $res = $this->obj->save(['status' => $data['status']],['id' => $data['id']]);
    //     if($res){
    //         $this->success('操作成功');
    //     }else{
    //         $this->error('操作失败');
    //     }
    // }
}
